<template>
  <div>
    <BasicTable @register="registerTable">
      <template #headerTop>
        <Alert v-if="checkedKeys.length > 0" type="info" show-icon style="position: relative">
          <template #message>
            <div>
              <span>已选中{{ checkedKeys.length }}条记录</span>
              <div style="position: absolute; top: 4px; right: 10px">
                <Tooltip title="删除">
                  <a-button type="text" @click="handleSelectedDelete">
                    <Icon :icon="ICON.DELETE" color="#0960bd" />
                  </a-button>
                </Tooltip>
              </div>
            </div>
          </template>
        </Alert>
      </template>
      <template #tableTitle>
        <Button class="mr-2" :type="isReadFlag" @click="isReadClick('未读')"> 未读 </Button>
        <Button class="mr-2" :type="allFlag" @click="isReadClick('所有')"> 所有 </Button>
      </template>
      <template #toolbar>
        <Tooltip title="全部标记为已读" @click="readClick()">
          <Icon icon="ic:outline-mark-email-read" size="23" style="margin-right: 10px" />
        </Tooltip>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <TableAction
            :actions="[
              {
                icon: 'ant-design:edit-filled',
                tooltip: {
                  title: '编辑',
                  placement: 'top',
                },
                ifShow: () => {
                  return !hasPermission('CUSTOMER_USER');
                },
                onClick: editInBox.bind(null, record),
              },
              {
                icon: 'ant-design:check-circle-outlined',
                tooltip: {
                  title: record?.status === 'SENT' ? '标记为已读' : '已读',
                  placement: 'top',
                },
                onClick: MarkAsRead.bind(null, record),
                disabled: record?.status === 'SENT' ? false : true,
              },
              {
                icon: 'ic:baseline-delete',
                tooltip: {
                  title: '删除',
                  placement: 'top',
                },
                onClick: deleteOneInbox.bind(null, record),
              },
            ]"
          />
        </template>
      </template>
    </BasicTable>
  </div>
  <!--编辑弹窗-->
  <EditModal
    @register="editRegisterModal"
    :access-key="accessKey"
    :edit-modal-data="editModalData"
    v-if="!hasPermission('CUSTOMER_USER')"
  />
</template>

<script lang="ts" setup>
  import EditModal from './EditModal.vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { inboxColumns, inBoxsearchFormSchema } from '../data/notification.data';
  import { tableFormStyleSetting, tableStyleSetting } from '/@/settings/thingsBoardDesign';
  import { onMounted, ref } from 'vue';
  import { useModal } from '/@/components/Modal';
  import Icon from '/@/components/Icon/src/Icon.vue';
  import {
    getNotificationListList,
    readTheInbox,
    deleteTheInbox,
    setRead,
  } from '/@/api/thingsborad/notification/notification';
  import { notificationsParams } from '/@/api/thingsborad/notification/model/notificationsModel';
  import { Button, Tooltip, Alert } from 'ant-design-vue';
  import dayjs from 'dayjs';
  import { inboxType } from '../data/notification.data';
  import { ICON } from '/@/enums/iconEnum';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { usePermission } from '/@/hooks/web/usePermission';
  const { hasPermission } = usePermission();
  // 获取用户登录信息
  //收件箱所有标记
  let allFlag = ref<any>('ghost');
  // 消息通知框
  const { createConfirm } = useMessage();
  //收件箱未读标记
  let isReadFlag = ref<any>('primary');
  //多选数组
  let checkedKeys = ref<any>([]);
  //请求参数
  let params = ref<notificationsParams>({
    pageSize: 10,
    page: 0,
    sortProperty: 'createdTime',
    sortOrder: 'DESC',
  });
  // 标签页监听回调
  let accessKey = ref('0');
  //表格编辑事件
  let editModalData: any = ref<any>({
    data: '',
    title: '',
    alarmSeverity: '',
  });

  let tableList = ref<any>([]);
  onMounted(() => {
    setProps({
      api: getNotificationListList,
      beforeFetch: (val) => {
        params.value.page = val.page - 1;
        params.value.pageSize = val.pageSize;
        params.value.sortOrder = val.order == 'ascend' ? 'ASC' : 'DESC';
        params.value.sortProperty = 'createdTime';
        params.value.unreadOnly = true;
        if (val.name === null) {
          params.value.textSearch = undefined;
        } else {
          params.value.textSearch = val.name;
        }
        return params.value;
      },
      afterFetch: (res) => {
        tableList.value = [];
        if (res.length === 0) {
          return tableList.value;
        }
        res.forEach((item) => {
          tableList.value.push({
            createdTime: dayjs(item.createdTime).format('YYYY-MM-DD HH:mm:ss'),
            type: inboxType[item.type],
            subject: item.subject,
            text: item.text,
            id: item.id.id,
            status: item.status,
            actionButtonConfig: item.additionalConfig.actionButtonConfig,
            info: item.info,
          });
        });
        return tableList.value;
      },
      fetchSetting: {
        pageField: 'page',
        sizeField: 'pageSize',
        listField: 'data',
        totalField: 'totalElements',
      },
    });
  });
  //表格初始化
  const [registerTable, { reload, setProps }] = useTable({
    columns: inboxColumns,
    ...tableStyleSetting,
    formConfig: {
      layout: 'horizontal',
      schemas: inBoxsearchFormSchema,
      showAdvancedButton: false,
      submitFunc: async () => {
        reload();
      },
      ...tableFormStyleSetting,
      actionColOptions: {
        md: { span: 8, offset: 16 },
        lg: { span: 6, offset: 16 },
        xl: { span: 4, offset: 16 },
        xxl: { span: 4, offset: 16 },
      },
    },
    rowKey: 'id',
    rowSelection: {
      type: 'checkbox',
      selectedRowKeys: checkedKeys,
      onSelect: onSelect,
      onSelectAll: onSelectAll,
    },
  });
  // 初始化编辑弹窗
  const [editRegisterModal, { openModal: openEditModal, setModalProps: setEditModalProps }] =
    useModal();
  //是否未读点击事件
  function isReadClick(type: string) {
    if (type === '未读') {
      isReadFlag.value = 'primary';
      allFlag.value = 'ghost';
      setProps({
        api: getNotificationListList,
        beforeFetch: (val) => {
          params.value.page = val.page - 1;
          params.value.pageSize = val.pageSize;
          params.value.sortOrder = val.order == 'ascend' ? 'ASC' : 'DESC';
          params.value.sortProperty = 'createdTime';
          params.value.unreadOnly = true;
          if (val.name === null) {
            params.value.textSearch = undefined;
          } else {
            params.value.textSearch = val.name;
          }
          return params.value;
        },
        afterFetch: (res) => {
          tableList.value = [];
          if (res.length === 0) {
            return tableList.value;
          }
          res.forEach((item) => {
            tableList.value.push({
              createdTime: dayjs(item.createdTime).format('YYYY-MM-DD HH:mm:ss'),
              type: inboxType[item.type],
              subject: item.subject,
              text: item.text,
              id: item.id.id,
              status: item.status,
              actionButtonConfig: item.additionalConfig.actionButtonConfig,
              info: item.info,
            });
          });
          return tableList.value;
        },
        fetchSetting: {
          pageField: 'page',
          sizeField: 'pageSize',
          listField: 'data',
          totalField: 'totalElements',
        },
      });
      reload();
    } else {
      isReadFlag.value = 'ghost';
      allFlag.value = 'primary';
      setProps({
        api: getNotificationListList,
        beforeFetch: (val) => {
          params.value.page = val.page - 1;
          params.value.pageSize = val.pageSize;
          params.value.sortOrder = val.order == 'ascend' ? 'ASC' : 'DESC';
          params.value.sortProperty = 'createdTime';

          if (val.name === null) {
            params.value.textSearch = undefined;
          } else {
            params.value.textSearch = val.name;
          }
          return params.value;
        },
        afterFetch: (res) => {
          tableList.value = [];
          if (res.length === 0) {
            return tableList.value;
          }
          res.forEach((item) => {
            tableList.value.push({
              createdTime: dayjs(item.createdTime).format('YYYY-MM-DD HH:mm:ss'),
              type: inboxType[item.type],
              subject: item.subject,
              text: item.text,
              id: item.id.id,
              status: item.status,
              actionButtonConfig: item.additionalConfig.actionButtonConfig,
              info: item.info,
            });
          });
          return tableList.value;
        },
        fetchSetting: {
          pageField: 'page',
          sizeField: 'pageSize',
          listField: 'data',
          totalField: 'totalElements',
        },
      });

      params.value.unreadOnly = false;
      reload();
    }
  }
  // 一建已读
  async function readClick() {
    try {
      let data: any = {
        headers: {
          normalizedNames: {},
          lazyUpdate: null,
        },
        params: {
          updates: null,
          cloneFrom: null,
          encoder: {},
          map: null,
          interceptorConfig: {
            ignoreLoading: false,
            ignoreErrors: false,
            resendRequest: false,
          },
        },
      };
      await setRead(data);
      reload();
    } catch (error) {}
  }
  // 多选删除
  const handleSelectedDelete = () => {
    createConfirm({
      iconType: 'info',
      title: `确定要删除      '${checkedKeys.value.length}'      个通知吗？`,
      content: '请注意：确认后，通知及其所有相关数据将不可恢复。',
      onOk: async () => {
        for (const item of checkedKeys.value) {
          await deleteTheInbox(`/${item}`);
        }
        reload();
        checkedKeys.value = [];
      },
    });
  };

  // 多选
  function onSelect(record, selected) {
    if (selected) {
      checkedKeys.value = [...checkedKeys.value, record.id];
    } else {
      checkedKeys.value = checkedKeys.value.filter((id) => id !== record.id);
    }
  }
  // 全选
  function onSelectAll(selected, _selectedRows, changeRows) {
    const changeIds = changeRows.map((item) => item.id);
    if (selected) {
      checkedKeys.value = [...checkedKeys.value, ...changeIds];
    } else {
      checkedKeys.value = checkedKeys.value.filter((id) => {
        return !changeIds.includes(id);
      });
    }
  }
  //标记为已读
  async function MarkAsRead(record: Recordable) {
    if (record.status !== 'SENT') {
      return;
    }
    let paramsURL = '/' + record.id + '/read';
    await readTheInbox(paramsURL);
    isReadClick('所有');
  }
  // 删除收件箱单条信息
  async function deleteOneInbox(record: Recordable) {
    createConfirm({
      iconType: 'info',
      title: `您确定要删除该通知吗？`,
      content: '请注意，在确认后，通知将无法恢复。',
      onOk: async () => {
        params.value.unreadOnly = isReadFlag.value !== 'ghost';
        await deleteTheInbox(`/${record.id}`);
        reload();
      },
    });
  }
  editInBox;
  function editInBox(record: Recordable) {
    setEditModalProps({
      showCancelBtn: false,
      showOkBtn: false,
      width: 500,
    });
    editModalData.value = {
      data: record,
      title: record.subject,
      alarmSeverity: record.alarmSeverity !== undefined ? record.alarmSeverity : 'MAJOR',
    };
    openEditModal(true, null);
  }
</script>
